package com.honkentuber.chat;

import java.util.List;

import org.json.simple.JSONObject;

import com.google.appengine.api.datastore.KeyFactory;
import com.honkentuber.AppContext;

public class RoomListServlet extends ChatBaseServlet {
  private static final long serialVersionUID = 3160171517137130469L;

  private static List<Room> getRooms(AppContext ctx) {
    ChatContext chatCtx = (ChatContext) ctx;
    ChatDatabase db = chatCtx.getChatDb();
    String creatorKey = ctx.req.getParameter("creatorKey");
    if (creatorKey != null && creatorKey.length() > 0) {
      return db.fetchRoomsByCreator(KeyFactory.stringToKey(creatorKey));
    }
    String creatorEmail = ctx.req.getParameter("creatorEmail");
    if (creatorEmail != null && creatorEmail.length() > 0) {
      return db.fetchRoomsByCreatorEmail(creatorEmail);
    }
    return db.fetchRooms();
  }

  @Override
  protected String newJspResponse(AppContext ctx) {
    ctx.req.setAttribute("rooms", getRooms(ctx));
    return "/roomlist.jsp";
  }

  @Override
  protected JSONObject newJsonResponse(AppContext ctx) {
    return Room.toJson(getRooms(ctx));
  }
}